<template>
    <div class="message-container">
        <!-- 消息列表容器 -->
        <div class="message-list-wrapper" ref="message_list_wrapper">
            <div class="message-single-button" v-if="(total_message>0)" 
                @click="get_history_message(current_chat?.room_id,'loadmore')">拉取历史</div>
            <div 
                v-if="message_data.length > 0"
                v-for="(item, index) in message_data" 
                :key="index"
                class="message-list"
                :class="item.sender_id ==String(userid) ? 'sender' : 'receiver'"
            >
                    <div v-if="index/20==0" class="message-column-time">
                        {{deal_time(item.messages_id)}}
                    </div>

                <div 
                    v-if="item.sender_id !=String(userid)"
                    class="user-avatar left-avatar"
                >
                   <img  :src=render_sender_image(item.sender_id)  style="width: 100%;height: 100%;border-radius: 50%;">
                </div>
                <div class="message-content">
                    {{ item.message }}
                </div>
                <div 
                    v-if="item.sender_id ==String(userid)"
                    class="user-avatar right-avatar"
                >       
                     <img :src="user_header_image || '/public/yonghu.png'" style="width: 100%;height: 100%;border-radius: 50%;">
                </div>
            </div>
        </div>
        <!-- INTERACT 固定在底部 -->
        <INTERACT
            v-model:show_interact="show_interact"
            @send_message="handle_send_message"
            v-model:user_input_text="user_input_text"
            style="position: sticky; border: none; bottom: -10px; margin: -10px 0; box-shadow: 0 0 20px 10px rgba(0, 0, 0, 0.05);" 
        />
    </div>
</template>

<script setup>
import { ref, watch, onMounted, inject, onBeforeUnmount,onBeforeMount, computed, reactive, nextTick } from 'vue'
import { get_double_message_by_room_id, get_group_message_by_room_id } from "@/api/chat/message.js"
import { flush_room_stream } from "@/api/chat/room.js"
import INTERACT from "./interact.vue"
let message_list_wrapper = ref(null)
const total_message = computed(() => { 
    return (chat.value.get_room_message_meta(current_chat.value?.room_id)?.total || 0)
            -
        (message_data.value.length || 0)
})
const show_interact = computed(() => { 
    return current_chat.value!==null
})

const current_model = defineModel('current_model', {
    type: String,
    required: true
})
// 依赖注入
const chat = inject('chat')()
const client = inject('chat_client')
const chat_cache = inject('chat_cache')
const room_stream = inject('room_stream')

let user_header_image = ref(null)
let user_input_text = ref("")

// 当前聊天室信息
const current_chat =defineModel('current_chat')
// 用户ID
let userid = ref(null)

// 消息数据和缓存
const users_info_cache = defineModel('users_info_cache', { required: true })
const message_data = defineModel("message_data", {default:[]})
const message_cache = defineModel('message_cache', {default: {}})// 内存缓存，存储不同聊天室的消息,这里能实现的原因是,该模块是通过room_id改变的渲染
const last_stream_cache = defineModel('last_stream_cache',{default: {}}) // 存储每个聊天室的最后stream时间

// 定时器
let poll_timer = null
const POLL_INTERVAL = 3000

const deal_time =(timestampStr) =>{
  const timestamp = timestampStr.split('-')[0];
  const timestampNumber = parseInt(timestamp, 10);
  const date = new Date(timestampNumber);
  if (isNaN(date.getTime())) {
    throw new Error('Invalid timestamp');
  }
  const formattedDate = date.toLocaleString();
  return formattedDate;
}
 

const render_sender_image = (id) => {
    const headerImage = users_info_cache.value?.[id]?.head_image;
    const roomImage = users_info_cache.value?.[current_chat.value?.room_id]?.[id]?.head_image;
    const fallbackImage = '/public/yonghu.png';
    
    return headerImage || roomImage || fallbackImage;
};

const sroll_to_bottom = () => {
    if (message_list_wrapper.value) {
        message_list_wrapper.value.scrollTop = message_list_wrapper.value.scrollHeight;
    }
}   


// 发送消息处理
const handle_send_message = async () => {
    const message = user_input_text.value
    const middle_data={sender_id:userid.value,message:message}
    // 无论怎样先push新消息,
    message_data.value = [...message_data.value, middle_data]
    client.sendMessage(
        'send_message',
        {
            room_type: current_chat.value['type'],
            room_id: current_chat.value['room_id'],
            content: message,
            sender_id: userid.value,
            receiver_id: chat.value?.get_current_user_chat_info(current_chat.value['room_id'])?.friend_info?.id,
        },
    )
    user_input_text.value = ''
    await nextTick()
    // 实际应该增加补丁是否发送成功
    sroll_to_bottom()
}

// 从IndexedDB获取历史消息
const get_history_message = async (room_id, type = "init", limit = 20) => {
    try {
        const last_time = (chat.value.get_room_message_meta(room_id) || {})['oldestMessageId'] || null;
        const data = await chat_cache.getMessagesByRoom(room_id, limit, last_time);
        console.log(data,last_time);
        chat.value.set_room_message_meta(room_id, "total", data.total);
        chat.value.set_room_message_meta(room_id, "oldestMessageId", data.oldestMessageId);
        
        if (type === "init") {
            return data.messages || [];
        } else {
            const newMessages = Array.isArray(data.messages) ? data.messages : [];
            // 将旧消息放在现有消息的前面
            message_data.value = [...newMessages, ...message_data.value];
            message_cache.value[room_id] = [...newMessages, ...message_cache.value[room_id]];
        }
        console.log(message_data.value);
    } catch (error) {
        console.error("Failed to get history messages:", error);
        return [];
    }
};


// 获取服务器消息并更新缓存
const get_message = async (room_id, type) => {
    try {
        const indexStream = await room_stream.getData(room_id)
        const last_stream = last_stream_cache?.value[room_id] || 
                          indexStream?.stream_time ||  0
        let server_data;
        if (type === 'double') {
         
            server_data = await get_double_message_by_room_id(room_id, userid.value, 0, 1, last_stream)
        } else { 
            server_data = await get_group_message_by_room_id(room_id, userid.value, 0, 1, last_stream)
        }
        const new_messages = server_data?.data || []
        if (new_messages.length > 0) {
            // 合并消息，避免重复
            const existing_messages = message_cache.value[room_id] || []
            const unique_new_messages = new_messages.filter(new_msg =>
                !existing_messages.some(existing_msg =>
                    existing_msg.messages_id === new_msg.messages_id
                )
            )
            if (unique_new_messages.length > 0) {
                const updated_messages = [...existing_messages, ...unique_new_messages]

                // 更新内存缓存
                message_cache.value[room_id] = updated_messages
                message_data.value = [...updated_messages]
                // 更新IndexedDB缓存
                await chat_cache.putAllData(unique_new_messages)
                // 更新stream时间
                const new_stream_time = server_data.meta.stream_time
                // 若无更新返回的是0,主要是为了处理群组和个人的方案
                if (new_stream_time) {
                    //双更新
                    await flush_room_stream(room_id, userid.value, new_stream_time)
                    // 认为用户视图窗口就是已读
                    await room_stream.putData({
                        room_id: room_id,
                        stream_time: new_stream_time,
                        unread: 0,
                        last_message:
                            unique_new_messages[unique_new_messages.length - 1]
                            ||
                            message_cache.value[room_id][message_cache.value[room_id].length - 1]
                    })
                    last_stream_cache.value[room_id] = new_stream_time
                }
            }
        } 
    } catch (error) {
    }
}

// 启动轮询
const start_polling = () => {
    // 清空轮询,避免重复启动
    stop_polling()
    poll_timer = setInterval(async () => {
        if (current_chat.value?.room_id && current_chat.value?.type) {
            await get_message(current_chat.value.room_id, current_chat.value.type)
        }
    }, POLL_INTERVAL)
}

// 停止轮询
const stop_polling = () => {
    if (poll_timer) {
        clearInterval(poll_timer)
        poll_timer = null
    }
}

// 切换聊天室时加载消息
const load_chat_messages = async (new_chat) => {
    if (!new_chat?.room_id) return
    // 检查内存缓存
    if (message_cache.value[new_chat.room_id]) {
        message_data.value = message_cache.value[new_chat.room_id]
        return
    } else { 
        message_data.value = []
    }
    // 检查IndexedDB缓存
    const history_messages = await get_history_message(new_chat.room_id)
    if (history_messages.length > 0) {
        message_cache.value[new_chat.room_id] = history_messages
        message_data.value = history_messages
    }
    // 从服务器获取最新消息
    await get_message(new_chat.room_id, new_chat.type)
}

// 监听当前聊天室变化
watch(() => current_chat.value, async (new_chat, old_chat) => {
   
    if (!new_chat || new_chat.room_id === old_chat?.room_id) return
    await load_chat_messages(new_chat)
    message_list_wrapper.value.scrollTop = message_list_wrapper.value.scrollHeight;
    start_polling()
    
}, { immediate: true })

// 组件生命周期
onBeforeMount(async () => { 
    userid.value = chat.value?.get_user_info()?.id
    user_header_image.value = chat.value?.get_user_info()?.head_image
})

onMounted(() => {
    start_polling()
   
})

onBeforeUnmount(() => { 
    stop_polling()
    // 清理内存缓存
    message_cache.value = {}
    last_stream_cache.value = {}
})
</script>

<style scoped>
.message-container {
    box-sizing: border-box;
    position: relative;
    padding: 10px;
    overflow-y: auto;
    height: 100%;
    display: flex;
    flex-direction: column;
}
.message-single-button{
   text-align: center;
   user-select: none;
   color:#808695
}

.message-list-wrapper {
    flex: 1;
    overflow:inherit;
    width: 100%;
}
.message-list-wrapper::-webkit-scrollbar{
    display: none;
}

.message-list {
    display: flex;
    margin-bottom: 20px;
    max-width: 100%;
    position: relative;
}

.message-list.receiver {
    justify-content: flex-start;
}

.message-list.sender {
    justify-content: flex-end;
}

.user-avatar {
    width: 32px;
    height: 32px;
    border-radius: 50%;
    background-color: #ccc;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
}

.left-avatar {
    margin-right: 10px;
}

.right-avatar {
    margin-left: 10px;
}

.message-content {
    padding: 8px 12px;
    border-radius: 8px;
    background-color: #f0f0f0;
    word-break: break-word;
    max-width: 70%;
}

.message-list.sender .message-content {
    background-color: #1890ff;
    color: white;
}
.message-column-time{
    color: #808695;
    font-size: 12px;
    text-align: center;
    margin: 10px 0;
    width: 100%;
    user-select: none;
    position: absolute;
    top:100%;
    margin-bottom: 20px;
}
</style>